package net.brucecooper.mindmapgadget.server;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

@SuppressWarnings("serial")
public class FreemindUploadServlet extends UploadDownloadServlet {

    XPath xp = XPathFactory.newInstance().newXPath();

    private JSONObject convertToJSON(Element e) throws JSONException, XPathExpressionException {
        JSONObject obj = new JSONObject();
        obj.put("n", e.getAttribute("TEXT"));

        NodeList kids = (NodeList) xp.evaluate("node", e, XPathConstants.NODESET); 
        if (kids.getLength() > 0) {
            JSONArray children = new JSONArray();
            for (int i = 0; i < kids.getLength(); i++) {
                children.put(convertToJSON((Element) kids.item(i)));
            }
            obj.put("c", children);
        }
        
        String icon = xp.evaluate("icon/@BUILTIN", e);
        if (icon != null && !"".equals(icon)) {
            obj.put("i", icon);
        }
        
        return obj;
    }

    @Override
    protected String convertToResult(String contents) throws IOException {
//        try {
//            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
//                    new ByteArrayInputStream(contents.getBytes()));
//            JSONObject result = convertToJSON((Element) doc.getDocumentElement().getElementsByTagName("node").item(0));
//            return result.toString(2);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            throw new IOException(ex);
//        }
        return contents;
    }

    @Override
    protected String getResultContentType() {
        return "text/json";
    }
    
    
}
